﻿using AutoMapper;
using MediatR;
using Medical.Api.Read.Application.Command.RecyclingCleaning;
using Medical.Api.Read.Dto.RecyclingCleaning;
using Medical.Domain.Enum;
using Medical.Domain.RecoveryCleaning;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Medical.Api.Read.Application.Handler.RecyclingCleaning
{
    /// <summary>
    /// 获取登记清洗的命令处理
    /// </summary>
    public class GetRegistrationCleaningCommandHandlter : IRequestHandler<GetRegistrationCleaningCommand, ApiResult<List<RegistrationCleaningDtos>>>
    {
        /// <summary>
        /// 清洗登记仓储
        /// </summary>
        private readonly IBaseRepository<CleaningRegistration> cleaningRegistrationRep;

        /// <summary>
        /// AutoMapper
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="cleaningRegistrationRep">清洗登记仓储</param>
        /// <param name="mapper">AutoMapper</param>
        public GetRegistrationCleaningCommandHandlter(IBaseRepository<CleaningRegistration> cleaningRegistrationRep, IMapper mapper)
        {
            this.cleaningRegistrationRep = cleaningRegistrationRep;
            this.mapper = mapper;
        }

        /// <summary>
        /// 处理方法
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>清洗登记列表</returns>
        public async Task<ApiResult<List<RegistrationCleaningDtos>>> Handle(GetRegistrationCleaningCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 获取所有未删除待清洗的清洗登记记录
                var cleaningRegistrations = cleaningRegistrationRep.GetAll().Where(x=>x.CleaningState== RecoveryStatusEnum.待清洗&&!x.IsDeleted)
                    .OrderByDescending(c => c.StartTime) // 按清洗开始时间倒序排列，最新的在前
                    .ToList();
                // 映射到DTO
                var cleaningDtos = mapper.Map<List<RegistrationCleaningDtos>>(cleaningRegistrations);

                return new ApiResult<List<RegistrationCleaningDtos>>
                {
                    Code = ApiEnums.Success,
                    Data = cleaningDtos,
                    Msg = "获取清洗登记列表成功"
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<List<RegistrationCleaningDtos>>
                {
                    Code = ApiEnums.Fail,
                    Data = null,
                    Msg = $"获取清洗登记列表失败: {ex.Message}"
                };
            }
        }
    }
}
